﻿using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using SqlSugerexample.Models;
using SqlSugerexample.Repositories;
using SqlSugerexample.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace SqlSugerexample.ViewModels
{
    public class MainViewModel : ObservableObject
    {
        private readonly UserRepository _userRepository = new UserRepository();
        private ObservableCollection<User> _users;
        private int _currentPage = 1;
        private int _pageSize = 10;
        private string _searchText;

        public ObservableCollection<User> Users
        {
            get => _users;
            set => SetProperty(ref _users, value);
        }

        public string SearchText
        {
            get => _searchText;
            set => SetProperty(ref _searchText, value);
        }

        public ICommand LoadUsersCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand SortByNameCommand { get; }
        public ICommand SearchCommand { get; }

        public MainViewModel()
        {
            LoadUsersCommand = new RelayCommand(async () => await LoadUsersAsync());
            NextPageCommand = new RelayCommand(async () => await NextPageAsync());
            PreviousPageCommand = new RelayCommand(async () => await PreviousPageAsync());
            SortByNameCommand = new RelayCommand(async () => await SortByNameAsync());
            SearchCommand = new RelayCommand(async () => await SearchUsersAsync());

            // 加载初始用户数据
            LoadUsersCommand.Execute(null);
        }

        private async Task LoadUsersAsync()
        {
            var users = await _userRepository.GetAllAsync();
            Users = new ObservableCollection<User>(users);
        }

        private async Task NextPageAsync()
        {
            _currentPage++;
            var users = _userRepository.GetPagedUsers(_currentPage, _pageSize);
            Users = new ObservableCollection<User>(users);
        }

        private async Task PreviousPageAsync()
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                var users = _userRepository.GetPagedUsers(_currentPage, _pageSize);
                Users = new ObservableCollection<User>(users);
            }
        }

        private async Task SortByNameAsync()
        {
            var sortedUsers = _userRepository.GetSortedUsersByName(_currentPage, _pageSize);
            Users = new ObservableCollection<User>(sortedUsers);
        }

        private async Task SearchUsersAsync()
        {
            var filteredUsers = _userRepository.SearchUsersByName(SearchText);
            Users = new ObservableCollection<User>(filteredUsers);
        }
    }
}
